package view;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Scroller;

public class TraceUserScalePicLayout extends ViewGroup{

	
	private String TAG = TraceUserScalePicLayout.class.getSimpleName();
	
	
	 
	Scroller mScroller;
	VelocityTracker mVelocityTracker;

	public TraceUserScalePicLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		
		
		mScroller = new Scroller(context);
		
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
		
	}

	
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// TODO Auto-generated method stub
		int childLeft = 0;
		final int childCount = getChildCount();
		System.out.println("childCount: "+childCount);
		for (int i = 0; i < childCount; i++) {
			final View childView = getChildAt(i);
			if (childView.getVisibility() != View.GONE) {
				final int childWidth = childView.getMeasuredWidth();
				childView.layout(childLeft, 0, childLeft + childWidth,
						childView.getMeasuredHeight());
				childLeft += childWidth;
			}
		}
		
	}
 
	
 
	///*
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		
		
		// The children are given the same width and height as the scrollLayout
		final int count = getChildCount();
		System.out.println("onMeasure count: "+count);
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}
		
		
	}
	//*/
	
	View view_target;
	public void SetView(View view){
		view_target = view;
	}
	
	
	void ScaleView(Matrix matrix){
	
		ImageView iv = (ImageView)view_target; 
		iv.setImageMatrix(matrix);
		
	}
	
	
	private static final int TOUCH_STATE_REST = 0;
	private static final int TOUCH_STATE_SCROLLING = 1;
	private static final int SNAP_VELOCITY = 600;
	private int mTouchState = TOUCH_STATE_REST;
	private int mTouchSlop;
	private float mLastMotionX;
	private float mLastMotionY;
	
	
	///*
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		Log.e(TAG, "onInterceptTouchEvent-slop:" + mTouchSlop);
		final int action = ev.getAction();
		if ((action == MotionEvent.ACTION_MOVE)
				&& (mTouchState != TOUCH_STATE_REST)) {
			return true;
		}
		final float x = ev.getX();
		final float y = ev.getY();
		switch (action) {
		case MotionEvent.ACTION_MOVE:
			final int xDiff = (int) Math.abs(mLastMotionX - x);
			if (xDiff > mTouchSlop) {
				mTouchState = TOUCH_STATE_SCROLLING;
			}
			break;
		case MotionEvent.ACTION_DOWN:
			mLastMotionX = x;
			mLastMotionY = y;
			
			mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST
					: TOUCH_STATE_SCROLLING;
			
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		
		Log.e(TAG, "onInterceptTouchEvent-mTouchState:" + mTouchState);
		
		return mTouchState != TOUCH_STATE_REST;
	}
	//*/
	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.e(TAG, "onTouchEvent");
		
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(event);
		final int action = event.getAction();
		final float x = event.getX();
		final float y = event.getY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			//Log.e(TAG, "event down!");
			if (!mScroller.isFinished()) {
				mScroller.abortAnimation();
			}
			mLastMotionX = x;
			
			//---------------New Code----------------------
			mLastMotionY = y;
			//---------------------------------------------
			
			break;
		case MotionEvent.ACTION_MOVE:
			int deltaX = (int) (mLastMotionX - x);
			
			//---------------New Code----------------------
			int deltaY = (int) (mLastMotionY - y);
	//		if(Math.abs(deltaX) < 200 && Math.abs(deltaY) > 10)
	//			break;
			mLastMotionY = y;
			//-------------------------------------
			
			mLastMotionX = x;
			scrollBy(0, deltaY);
			break;
		case MotionEvent.ACTION_UP:
			//Log.e(TAG, "event : up");
			// if (mTouchState == TOUCH_STATE_SCROLLING) {
			final VelocityTracker velocityTracker = mVelocityTracker;
			velocityTracker.computeCurrentVelocity(1000);
			int velocityX = (int) velocityTracker.getXVelocity();
			//Log.e(TAG, "velocityX:" + velocityX);
			/*
			if (velocityX > SNAP_VELOCITY && mCurScreen > 0) {
				// Fling enough to move left
				//Log.e(TAG, "snap left");
				snapToScreen(mCurScreen - 1);
			} else if (velocityX < -SNAP_VELOCITY
					&& mCurScreen < getChildCount() - 1) {
				// Fling enough to move right
				//Log.e(TAG, "snap right");
				snapToScreen(mCurScreen + 1);
			} else {
				snapToDestination();
			}
			*/
			if (mVelocityTracker != null) {
				mVelocityTracker.recycle();
				mVelocityTracker = null;
			}
			// }
			mTouchState = TOUCH_STATE_REST;
			break;
		case MotionEvent.ACTION_CANCEL:
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		return true;
	}
	/*
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		
		Log.d(TAG, "mLastMotionX: "+mLastMotionX+"  mLastMotionY: "+mLastMotionY);
		
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			
			break;
		case MotionEvent.ACTION_MOVE:
			smoothScrollBy((int)mLastMotionX, (int)mLastMotionY);
			
			break;
			
		case MotionEvent.ACTION_UP:
			
			break;
		}
		
		
		return true;
	}
	*/
	
	@Override
	public void computeScroll() {
		// TODO Auto-generated method stub
	
		
		// 是否到达终点
		if(mScroller.computeScrollOffset()){
			
			// 使偏移生效
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
		}
		
		
	}
	
    //调用此方法滚动到目标位置  
    public void smoothScrollTo(int fx, int fy) {  
        int dx = fx - mScroller.getFinalX();  
        int dy = fy - mScroller.getFinalY();  
        smoothScrollBy(dx, dy);  
    }  
  
    //调用此方法设置滚动的相对偏移  
    public void smoothScrollBy(int dx, int dy) {  
  
        //设置mScroller的滚动偏移量  
        mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy);  
        invalidate();//这里必须调用invalidate()才能保证computeScroll()会被调用，否则不一定会刷新界面，看不到滚动效果  
    } 
    
	
	
	/* ok
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:

			 if (mVelocityTracker == null) { 
		            mVelocityTracker = VelocityTracker.obtain();//获得VelocityTracker类实例 
			 }
			 else{	
				 mVelocityTracker.clear();
			 }
			 
			mVelocityTracker.addMovement(event);
			break;
			
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			mVelocityTracker.computeCurrentVelocity(1000);	
			float velocity_x = mVelocityTracker.getXVelocity();	// 有正负之分详情见引用的url
			float velocity_y = mVelocityTracker.getYVelocity();
			
			String str = "velocity_x: "+velocity_x + "velocity_y: "+velocity_y;
			 
			
			
			break;
			
		case MotionEvent.ACTION_MOVE:
			mVelocityTracker.addMovement(event);
			break;
			
		 
		}
		 
		
		return true;
		
	}
	*/
	
	/*
	@Override
	public boolean onTouchEvent(MotionEvent event) {
	//	System.out.println("onTouch");
		
		long delt_time =System.currentTimeMillis();
		System.out.println("逝去时间:" + delt_time);
		System.out.println("mode: "+mode);
		
		switch ( event.getAction() )
		{
		
		// 一个手指放下是拖拽
		case MotionEvent.ACTION_DOWN:
			
			//保持上次的矩阵
			m_LastMatrix.set(m_matrix);
			m_DownF.set(event.getX(), event.getY());
			
			mode =DRAG;
			break;
			
			// 两个手指放下,是缩放
		case MotionEvent.ACTION_POINTER_DOWN:
			m_OldDist =spacing(event);
			if(m_OldDist > 10.0f){
				
				m_LastMatrix.set(m_matrix);
				
				midPoint(m_Mid, event); // 得到两点之间的中点
				mode =ZOOM;
			}
			
			break;
			
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			mode =0;
			break;
			
		case MotionEvent.ACTION_MOVE:
			if(mode == DRAG){
				
				float dx =event.getX()-m_DownF.x;
				float dy =event.getY()-m_DownF.y;
				System.out.printf("dx:%f,,dy:%f", dx, dy);
				
				m_matrix.set(m_LastMatrix); // 设置为上次使用的矩阵	
				m_matrix.postTranslate(dx, dy); 
				
					
			}
			else if( mode == ZOOM){
				m_NewDist =spacing(event);
				if(m_NewDist > 10.0f){
					
					System.out.printf("OldDist:%f,NewDist:%f,s:%f", 
							m_OldDist, m_NewDist, m_NewDist/m_OldDist );
					float s =m_NewDist/m_OldDist ; 
					
					m_matrix.set(m_LastMatrix);
//			/		m_matrix.postScale(s, s);
					m_matrix.postScale(s, s, m_Mid.x, m_Mid.y); //根据中点进行缩放
				}
					
			}
			
			break;
		}
		
		ScaleView(m_matrix);
		
		return true;
	}
	*/
	
	   /** Determine the space between the first two fingers */
	   private float spacing(MotionEvent event) {
	      float x = event.getX(0) - event.getX(1);
	      float y = event.getY(0) - event.getY(1);
	      return (float) Math.sqrt(x * x + y * y);
	   }

	   /** Calculate the mid point of the first two fingers */
	   private void midPoint(PointF point, MotionEvent event) {
	      float x = event.getX(0) + event.getX(1);
	      float y = event.getY(0) + event.getY(1);
	      point.set(x / 2, y / 2);
	   }
	
	   
	private   int mode =0;   
	private final int DRAG =1;
	private final int ZOOM =2;
	private Matrix m_matrix = new Matrix();
	private Matrix m_LastMatrix = new Matrix();
	private PointF m_DownF = new PointF();
//	private PointF m_UpF =new PointF();
	
	private float m_OldDist;
	private float m_NewDist;
	
	private PointF m_Mid =new PointF();
	
	
	
	
	
	
	
}
